const db = require('../db/index')
const util = require('util')
const { string } = require('joi')

const query = util.promisify(db.query).bind(db)

function getTree(results, keyId) {
    let arr = []
    for (idx in results) {
        if (results[idx].ps_level == 0) {
            if (keyId.length != 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                continue
            }
            // console.log(results);
            arr.push({
                id: results[idx].ps_id,
                authName: results[idx].ps_name,
                path: results[idx].ps_api_path,
                pid: results[idx].ps_pid,
                children: []
            })
        }
    }


    // 生成二级菜单
    for (idx in results) {
        if (results[idx].ps_level == 1) {
            for (var j = 0; j < arr.length; j++) {
                if (results[idx]['ps_pid'] == arr[j].id) {
                    if (keyId.length != 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                        continue
                    }
                    arr[j].children.push({
                        id: results[idx].ps_id,
                        authName: results[idx].ps_name,
                        path: results[idx].ps_api_path,
                        pid: results[idx].ps_pid,
                        children: []
                    })
                }
            }

        }
    }
    // console.log(results);
    // 生成三级菜单
    for (idx in results) {
        if (results[idx].ps_level == 2) {
            for (var j = 0; j < arr.length; j++) {
                var secondMenu = arr[j].children;
                // console.log(secondMenu);
                for (var i = 0; i < secondMenu.length; i++) {
                    if (results[idx]['ps_pid'] == secondMenu[i].id) {
                        if (keyId.length != 0 && keyId.indexOf(results[idx].ps_id + '') == -1) {
                            continue
                        }
                        secondMenu[i].children.push({
                            id: results[idx].ps_id,
                            authName: results[idx].ps_name,
                            path: results[idx].ps_api_path,
                            pid: results[idx].ps_pid + ',' + arr[j].id,
                        })
                    }
                }
            }
        }
    }
    return arr
}
exports.rightList = (req, res) => {
        // res.ResData("获取权限列表")
        // 接收参数
        let type = req.params.type;
        // console.log(type); 成功
        // 判断参数类型
        if (!type || type != 'list' && type != "tree")
            return res.ResData("参数错误")
                // 根据参数操作数据库
        var sql = 'select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)'
        db.query(sql, (err, results) => {
            if (err) res.ResData("获取列表失败")
                // console.log(results)
            if (type == 'list') {
                var arr = [];
                for (idx in results) {
                    let result = results[idx]
                    arr.push({
                        "id": result,
                        "authName": result.ps_name,
                        "level": result.ps_level,
                        "pid": result.ps_pid,
                        "path": result.ps_api_path
                    })
                }
                res.ResData("获取权限列表成功", 200, arr);
            } else {
                // 生成一次菜单
                var arr = getTree(results, [])
                res.ResData("获取权限列表成功", 200, arr)
            }
        })
    }
    // 角色列表
exports.rolesList = async(req, res) => {
    // res.ResData("角色列表")
    // 角色列表查询角色
    var sql1 = "select * from sp_role"
    var sql2 = 'select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)'
    try {
        var result1 = await query(sql1)
        var result2 = await query(sql2)
        let arr = [];
        for (idx in result1) {
            let keyId = result1[idx]['ps_ids'].split(",")
                // console.log(keyId)
            let obj = {

                "id": result1[idx].role_id,
                "roleName": result1[idx].role_name,
                "roleDesc": result1[idx].role_desc,
                "children": []
            }
            let tree = getTree(result2, keyId);
            // console.log(tree);
            obj.children = tree;
            arr.push(obj)
        }
        res.ResData("获取角色列表成功", 200, arr)
    } catch (err) {
        res.ResData(err)
    }

}

// 添加角色
exports.rolesAdd = (req, res) => {
    // res.ResData('添加用户')
    // console.log(req)
    var id = req.body.rolesid
    var name = req.body.rolesname
    var desc = req.body.rolesdesc
        // 检查角色是否存在
    var sql = 'select * from sp_role where role_id=?'
        // 添加数据

    db.query(sql, id, (err, result) => {
        // console.log(sql);
        if (err) return res.ResData(err)
        if (result.length > 0) {
            return res.ResData('用户id存在')
        }
        // 添加数据
        var sql1 = "insert into sp_role ( role_id,role_name,role_desc) values(?,?,?) "
        db.query(sql1, [id, name, desc], (err, data) => {
            if (err) return res.ResData(err)
            res.ResData('创建成功', 200, {
                "roleId": id,
                "roleName": name,
                "roleDesc": desc
            })
        })
    })




}

// 根据Id查询角色
exports.rolesQuiry = (req, res) => {
    // res.ResData('查询角色')

    var id = req.params.id
        // console.log(id);
    var sql = 'select * from sp_role where role_id=?'
    db.query(sql, [id], (err, result) => {
        if (err) return res.ResData(err)
        if (result.length > 0) {
            res.ResData('获取成功', 200, {
                "roleId": id,
                "roleName": result[0].role_name,
                "roleDesc": result[0].role_desc
            })
        }
    })
}

// 编辑提交角色
exports.rolesEdit = (req, res) => {
    // res.ResData('编辑提交角色')
    var id = req.params.id
        // console.log(id);
    var desc = req.body.roleDesc
        // console.log(name);
        // console.log(desc);
        // affectedRows 不知道是什么！！！！
    var sql = "update sp_role set role_desc=? where role_id=?"
    db.query(sql, [desc, id], (err, result) => {

            if (err) return res.ResData(err)


            if (result.affectedRows < 1) return res.ResData('更新角色信息失败')
            var sql = "select * from sp_role where role_id=? "
            db.query(sql, id, (err, resResult) => {
                // console.log(resResult[0])
                res.ResData('更新角色信息成功', 200, {
                    "roleId": resResult[0].role_id,
                    "roleName": resResult[0].role_name,
                    "roleDesc": resResult[0].role_desc
                })
            })
        })
        //    console.log(id);

}


// 删除角色
exports.deleteRoles = (req, res) => {
    // res.ResData('删除角色')
    var id = req.params.id
        // console.log(id);
    var sql = "delete from sp_role where role_id=?"
    db.query(sql, [id], (err, result) => {

        if (err) return res.ResData(err)
        if (result.affectedRows != 1) return res.ResData("删除失败")
        res.ResData("删除成功", 200)
    })

}

// 角色授权
exports.updateRoleRight = (req, res) => {
    // res.ResData('角色授权')
    // 获取角色ID
    const roleId = req.params.roleId;
    // console.log(req.body);
    // 参数验证
    if (roleId.trim() == '') return res.ResData('角色ID不能为空')
        // if (isNaN(parseInt(roleId))) return res.ResData('角色id必须是数字')
        // if (typeof(roleId) !== 'number') return res.ResData("角色id必须是数字")
    if (parseInt(roleId) !== roleId) return res.ResData('角色id必须是数字')
    if (string(roleId).indexOf('.') !== -1) return res.ResData('角色id必须是整数')

    var sql = "update sp_role set ps_ids=? where role_id=?"
    db.query(sql, [req.body.rids, roleId], (err, result) => {

        if (err) return res.ResData('角色授权失败')
        res.ResData('角色更新成功', 200)
    })
}

// 删除角色权限
exports.deleteRoleRight = async(req, res) => {
    // res.ResData('删除角色权限')
    // 参数验证
    // 获取角色ID
    const roleId = req.params.roleId;
    //  获取权限id
    const rightId = req.params.rightId
        // console.log(roleId);
        // console.log(rightId);
        // 参数验证
    if (roleId.trim() == '' && rightId.trim() == '') return res.ResData('角色ID和权限ID不能为空')
        // if (isNaN(parseInt(roleId))) return res.ResData('角色id必须是数字')
        // if (typeof(roleId) !== 'number') return res.ResData("角色id必须是数字")
    if (parseInt(roleId) != roleId && parseInt(rightId) != rightId) return res.ResData('角色id和权限id必须是数字')
    if (roleId.indexOf('.') != -1 && rightId.indexOf('.') != -1) return res.ResData('角色id必须是整数')
        // 逻辑
    var sql = "select * from sp_role where role_id=?"
    var sql2 = "update sp_role set ps_ids=? where role_id=?"
    var sql3 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    try {
        var result = await query(sql, roleId);
        // console.log(result);
        ps_ids = result[0].ps_ids.split(',');
        new_ps_ids = []
            // console.log(ps_ids);
        for (idx in ps_ids) {
            ps_id = ps_ids[idx]
            if (rightId == ps_id) {
                continue
            }
            new_ps_ids.push(ps_id)
        }
        // console.log(rightId);
        // console.log(new_ps_ids);
        news_ps_ids = new_ps_ids.join(',')
        var result2 = await query(sql2, [news_ps_ids, roleId])
            // console.log(result2);
        var result3 = await query(sql3)
            // console.log(result3);
        tree = getTree(result3, new_ps_ids)
            // console.log(tree);
        res.ResData("删除成功", 200, tree)
    } catch (err) {
        res.ResData(err)
    }
    // db.query(sql, roleId, (err, result) => {
    //     if (err) return res.ResData('获取角色信息失败!')
    //     ps_ids = result[0].ps_ids.split(',');
    //     console.log(ps_ids);
    //     new_ps_ids = []
    //     for (idx in ps_ids) {
    //         ps_id = ps_ids[idx]
    //         if (rightId == ps_id) {
    //             continue
    //         }
    //         new_ps_ids.push(ps_id)

    //     }
    //     // console.log(new_ps_ids);
    //     news_ps_ids = new_ps_ids.join(',')
    //         // console.log(new_ps_ids);
    //     var sql = "update sp_role set ps_ids=? where role_id=?"
    //     db.query(sql, [news_ps_ids, roleId], (err, result2) => {

    //         if (err) return res.ResData('删除失败')
    //         var sql2 = "select e.ps_id,e.ps_name,e.ps_pid,e.ps_level,d.ps_api_path from sp_permission e left join sp_permission_api d on(e.ps_id=d.ps_id)"
    //         db.query(sql2, (err, data) => {
    //             tree = getTree(data, new_ps_ids)
    //             return res.ResData(tree)
    //         })
    //         return res.ResData('删除成功', 200)

    //     })
    // })
}